package com.vipheyue.bigbusiness.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.convenientbanner.CBViewHolderCreator;
import com.bigkoo.convenientbanner.ConvenientBanner;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.lidroid.xutils.util.LogUtils;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.vipheyue.bigbusiness.R;
import com.vipheyue.bigbusiness.activity.EmployeeActivity;
import com.vipheyue.bigbusiness.activity.JobDetailActivity;
import com.vipheyue.bigbusiness.activity.JobWelfareListActivity;
import com.vipheyue.bigbusiness.activity.LoginActivity;
import com.vipheyue.bigbusiness.activity.SelectionCategoryActivity;
import com.vipheyue.bigbusiness.bean.Job;
import com.vipheyue.bigbusiness.bean.MyUser;
import com.vipheyue.bigbusiness.cityList.CityChoiceActivity;
import com.vipheyue.bigbusiness.utils.DensityUtil;
import com.vipheyue.bigbusiness.utils.GsonUtils;
import com.vipheyue.bigbusiness.utils.UriConfig;
import com.vipheyue.bigbusiness.view.CommonAdapter;
import com.vipheyue.bigbusiness.view.NetworkImageHolderView;
import com.vipheyue.bigbusiness.view.ViewHolder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.listener.FindListener;


public class ReNameFragment0 extends Fragment {
    View view;
    @Bind(R.id.rl_menu_left)
    RelativeLayout rl_menu_left;
    @Bind(R.id.tv_Menu_Title)
    TextView tv_Menu_Title;
    @Bind(R.id.iv_menu_right)
    ImageView iv_menu_right;
    @Bind(R.id.rl_menu_right)
    RelativeLayout rl_menu_right;
    @Bind(R.id.pull_refresh_list)
    PullToRefreshListView pull_refresh_list;
    @Bind(R.id.iv_menu_rightTitle)
    TextView iv_menu_rightTitle;
    @Bind(R.id.iv_Menu_leftImg)
    ImageView iv_Menu_leftImg;
    @Bind(R.id.tv_Menu_leftTitle)
    TextView tv_Menu_leftTitle;
    private List<String> networkImages = new ArrayList<>();
    private String[] images = {UriConfig.bannerUri + "1.jpg", UriConfig.bannerUri + "2.jpg", UriConfig.bannerUri + "3.jpg", UriConfig.bannerUri + "4.jpg", UriConfig.bannerUri + "5.jpg", UriConfig.bannerUri + "6.jpg", UriConfig.bannerUri + "7.jpg"};
    private CommonAdapter<Job> mAdapter;
    private List<Job> mDatas = new ArrayList<Job>();
    private int nowPageNum = 0;
    private int pageSize = 50;
    private static final int Fragment0_hot_cityResult = 3333;
    private static final int SelectionCategoryResult = 2222;
    private String selectWorkAreaType = null;
    private ConvenientBanner convenientBanner;
    private TextView tv_hot_city1;
    private TextView rl_hot4_text;
    private String search_jobType;
    private String search_companyName;
    private ArrayList<String> search_jobWelfare_list;
    private static final int JobWelfareListActivity_Result=3334;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.rename_fragment0, null);
        ButterKnife.bind(this, view);

        initView();
        mDatas.clear();
        initRefresh();
        setAdapter();
        initData(0);
        return view;
    }

    private void initView() {
        tv_Menu_Title.setText("巨业");
        iv_menu_rightTitle.setText("登录");
        iv_menu_rightTitle.setVisibility(View.VISIBLE);
        iv_Menu_leftImg.setVisibility(View.GONE);
        tv_Menu_leftTitle.setVisibility(View.VISIBLE);
        // 1，轮播图要单独存在，并且随处可用
        View bannerand4tabView = View.inflate(getActivity(), R.layout.bannerand4tab, null);
        pull_refresh_list.getRefreshableView().addHeaderView(bannerand4tabView);//TODO 添加头
        convenientBanner = ButterKnife.findById(pull_refresh_list, R.id.convenientBanner);
        startBanner();
        tv_hot_city1 = ButterKnife.findById(pull_refresh_list, R.id.tv_hot_city1);
        rl_hot4_text = ButterKnife.findById(pull_refresh_list, R.id.rl_hot4_text);
        ButterKnife.findById(pull_refresh_list, R.id.rl_hotcity).setOnClickListener(new hotButtonListener());
        ButterKnife.findById(pull_refresh_list, R.id.rl_hotPlace).setOnClickListener(new hotButtonListener());
        ButterKnife.findById(pull_refresh_list, R.id.rl_hot3).setOnClickListener(new hotButtonListener());
        ButterKnife.findById(pull_refresh_list, R.id.rl_hot4).setOnClickListener(new hotButtonListener());
        MyUser userInfo = BmobUser.getCurrentUser(getActivity(), MyUser.class);
        if (userInfo != null) {
            iv_menu_rightTitle.setText("退出");
        } else {
            iv_menu_rightTitle.setText("登录");
        }
    }

    private void initData(int getNumPage) {
        LogUtils.i("----------------------> initData ");
        BmobQuery<Job> query = new BmobQuery<Job>();
        query.setLimit(pageSize); // 限制最多10条数据结果作为一页
        query.setSkip(pageSize * getNumPage); // 忽略前10条数据（即第一页数据结果）
        query.order("-updatedAt");
        query.include("publisherCompany");// 希望在查询帖子信息的同时也把发布人的信息查询出来
        query.addWhereEqualTo("display", true);
        addCondition(query);
        query.findObjects(getActivity(), new FindListener<Job>() {
            @Override
            public void onSuccess(List<Job> object) {
                mDatas.addAll(object);
                LogUtils.i("数量:" + mDatas.size());
                nowPageNum = nowPageNum + 1;
                mAdapter.notifyDataSetChanged();
                // Call onRefreshComplete when the list has been refreshed.
                if (pull_refresh_list != null) {
                    pull_refresh_list.onRefreshComplete();
                }
            }

            @Override
            public void onError(int code, String msg) {
                if (pull_refresh_list != null) {
                    pull_refresh_list.onRefreshComplete();
                }

            }
        });
    }

    private void addCondition(BmobQuery<Job> query) {
        if (selectWorkAreaType != null) {
            query.addWhereEqualTo("workAreaType", selectWorkAreaType);
        }
        if (!TextUtils.isEmpty(search_jobType)) {
            query.addWhereEqualTo("jobType", search_jobType);
        }
        if (!TextUtils.isEmpty(search_companyName)) {
            query.addWhereContains("companyName", search_companyName);
        }
        if (search_jobWelfare_list != null && search_jobWelfare_list.size() > 0) {
            query.addWhereContainsAll("jobWelfareList",search_jobWelfare_list);
        }
    }


    private void initRefresh() {
        pull_refresh_list.setMode(PullToRefreshBase.Mode.BOTH);
        pull_refresh_list.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                mDatas.clear();
                nowPageNum = 0;
                initData(nowPageNum);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                String label = DateUtils.formatDateTime(getActivity(), System.currentTimeMillis(), DateUtils.FORMAT_SHOW_TIME | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_ALL);
                // Update the LastUpdatedLabel
                refreshView.getLoadingLayoutProxy().setLastUpdatedLabel(label);
                // Do work to refresh the list here.
                initData(nowPageNum);
            }

        });
    }

    private void setAdapter() {
        //mdatas 记得加数据进去
        mAdapter = new CommonAdapter<Job>(getActivity(), mDatas, R.layout.job_item) {
            @Override
            public void convert(ViewHolder helper, int position, Job item) {

                LogUtils.i("哈哈哈:" + item.getJobType());
                if (item.getJobTitle().trim().length() != 2) {
                    helper.setRoundTextSize(R.id.rlv_jobType, DensityUtil.sp2px(getActivity(), 10.00f));
                }
                helper.setRoundText(R.id.rlv_jobType, item.getJobType());
                helper.setText(R.id.tv_jobTitile, item.getJobTitle());
                helper.setText(R.id.tv_workAreaType, item.getWorkAreaType());
                helper.setText(R.id.tv_createTime, item.getUpdatedAt());
                helper.setText(R.id.tv_maxSalaryAndType, item.getMaxSalary() + "/" + item.getSalaryType());
            }
        };
        pull_refresh_list.setOnItemClickListener(new ItemClickListener());
        pull_refresh_list.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
    }

    @OnClick({R.id.tv_Menu_leftTitle, R.id.iv_menu_rightTitle})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_Menu_leftTitle:
                startActivityForResult(new Intent(getActivity(), CityChoiceActivity.class), Fragment0_hot_cityResult);
                break;
            case R.id.iv_menu_rightTitle:
                startActivity(new Intent(getActivity(), LoginActivity.class));
                getActivity().finish();
                break;
        }
    }


    public class hotButtonListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.rl_hotcity:
                    startActivityForResult(new Intent(getActivity(), CityChoiceActivity.class), Fragment0_hot_cityResult);
                    break;
                case R.id.rl_hotPlace:
                    MyUser userInfo = BmobUser.getCurrentUser(getActivity(), MyUser.class);
                    if (userInfo != null) {
                        startActivity(new Intent(getActivity(), EmployeeActivity.class));
                    } else {
                        startActivity(new Intent(getActivity(), LoginActivity.class));
                        getActivity().finish();
                    }
                    break;
                case R.id.rl_hot3:
                    startActivityForResult(new Intent(getActivity(), SelectionCategoryActivity.class), SelectionCategoryResult);
                    break;
                case R.id.rl_hot4:
                    startActivityForResult(new Intent(getActivity(), JobWelfareListActivity.class), JobWelfareListActivity_Result);
                    break;
            }
        }
    }

    private final class ItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            ListView listView = (ListView) parent;
            Job job = (Job) listView.getItemAtPosition(position);
            String jobStr = GsonUtils.toJson(job);
            Intent intent = new Intent(getActivity(), JobDetailActivity.class);
            intent.putExtra("jobStr", jobStr);
            startActivity(intent);
        }
    }

    private void startBanner() {
        //网络加载例子
        networkImages = Arrays.asList(images);
        convenientBanner.setPages(new CBViewHolderCreator<NetworkImageHolderView>() {
            @Override
            public NetworkImageHolderView createHolder() {
                return new NetworkImageHolderView();
            }
        }, networkImages)
                //设置两个点图片作为翻页指示器，不设置则没有指示器，可以根据自己需求自行配合自己的指示器,不需要圆点指示器可用不设
                .setPageIndicator(new int[]{R.drawable.ic_page_indicator, R.drawable.ic_page_indicator_focused})
                //设置指示器的方向
                .setPageIndicatorAlign(ConvenientBanner.PageIndicatorAlign.CENTER_HORIZONTAL)
                //设置翻页的效果，不需要翻页效果可用不设
                .setPageTransformer(ConvenientBanner.Transformer.DefaultTransformer);
        initImageLoader();
        //开始自动翻页
        convenientBanner.startTurning(5000);
    }

    //初始化网络图片缓存库
    private void initImageLoader() {
        //网络图片例子,结合常用的图片缓存库UIL,你可以根据自己需求自己换其他网络图片库
        DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder().
                showImageForEmptyUri(R.drawable.ic_default_adimage).cacheInMemory(true).cacheOnDisk(true).build();
        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(getActivity()).defaultDisplayImageOptions(defaultOptions).threadPriority(Thread.NORM_PRIORITY - 2).denyCacheImageMultipleSizesInMemory().diskCacheFileNameGenerator(new Md5FileNameGenerator()).tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (resultCode != -1) {
            return;
        }
        switch (requestCode) {
            case Fragment0_hot_cityResult:
                setResultForCityText(intent);
                break;
            case SelectionCategoryResult:
                setResultForSelectionCategory(intent);
                break;
            case JobWelfareListActivity_Result:
                setResultForSelectionCategory(intent);
                break;
        }
        super.onActivityResult(requestCode, resultCode, intent);
    }

    private void setResultForSelectionCategory(Intent intent) {
        search_jobType = intent.getStringExtra("search_jobType");
        search_companyName = intent.getStringExtra("search_companyName");
        search_jobWelfare_list = intent.getStringArrayListExtra("search_jobWelfare_list");
        mDatas.clear();
        initData(0);
        LogUtils.i("search_jobType"+search_jobType);
        LogUtils.i("search_companyName"+search_companyName);
    }

    private void setResultForCityText(Intent data) {
        selectWorkAreaType = data.getStringExtra("SelectCityName");
        if (TextUtils.isEmpty(selectWorkAreaType)) {
            tv_Menu_leftTitle.setText("南京");
        } else {
            tv_Menu_leftTitle.setText(selectWorkAreaType);
        }
        mDatas.clear();
        initData(0);
    }
    //ArrayList<Element> arrayList = new ArrayList<Element>(Arrays.asList(array));
//    List<Element> list = Arrays.asList(array);
}
